<?php
	session_start();
	
	/**
	 * Base class for all system services.
	 */
	class Service {
		
		/** The constructor of this object. */
		function __construct() {
			
		}
		
		/**
		 * Generates a session id for the user.
		 * @param $userID The user to generate the id for.
		 * @return The generated id.
		 */
		function allocateSession($userID) {
			
			$key = session_id() . "_" . $userID;
			$_SESSION[$key] = date("Y-m-d H:i:s");
			return $key;
		}
		
		/**
		 * Terminates the current user session.
		 * @param $sessionID The ID of the session to terminate.
		 */
		function terminateSession($sessionID) {
		
			unset($_SESSION[$sessionID]);
		}
		
		/**
		 * Checks if a user session is still valid.
		 * @param $sessionID The ID of the session to validate.
		 */
		function validateSession($sessionID) {
			
			if(!isset($_SESSION[$sessionID]) && $sessionID != "debug") {
				die("Session has expired.");
			}
		}
		
		/**
		 * Saves the given text to a system log file.
		 * @param $logString The text to log out to file.
		 */
		static function logOutput($logString) {
			
			$fileName = "logs/" . date("Ymd_His") . ".log";
			
			if(touch($fileName)) {
				
				// Let's make sure the file exists and is writable first.
				if(is_writable($fileName)) {
					
					// In our example we're opening $fileName in append mode.
					// The file pointer is at the bottom of the file hence 
					// that's where $logString will go when we fwrite() it.
					if(!$handle = fopen($fileName, 'w')) {
						echo "Cannot open file ($fileName)";
						exit;
					}
					
					// Write $logString to our opened file.
					if(fwrite($handle, $logString) === false) {
						echo "Cannot write to file ($fileName)";
						exit;
					}
					
					fclose($handle);
					
				} else {
					
					echo "The file $fileName is not writable";
				}
			}
		}
	}
?>